package cn.ppool.xmlmapper.builder.parse.model.func;

import cn.ppool.xmlmapper.builder.MapperBuilder;
import cn.ppool.xmlmapper.builder.parse.model.base.BaseFuncBO;
import cn.ppool.xmlmapper.builder.xml.XNode;
import cn.ppool.xmlmapper.exctption.FirstIfElseException;
import cn.ppool.xmlmapper.exctption.MultipleElseException;

import java.util.Map;

import static cn.ppool.xmlmapper.builder.parse.model.base.BaseTest.ELSE;
import static cn.ppool.xmlmapper.builder.parse.model.base.BaseTest.FUN_ELSE_ENUM;

public class WhereBO extends BaseFuncBO {
    public final static String TAG_NAME = "WHERE";

    public WhereBO(MapperBuilder configure, XNode parentNode, XNode currentNode) {
        super(configure, parentNode, currentNode);
    }

    @Override
    public void buildEntityModel() {

    }

    @Override
    public String complieEntity(Map<String, Object> allVar, Map<String, Object> sqlVar, StringBuilder sql, BaseFuncBO lastObject) {
        StringBuilder comSql = new StringBuilder();
        if (!sql.toString().toUpperCase().contains(WhereBO.TAG_NAME)) {
            comSql.append(" where \n");
        }
        //
        IfBO lastIfNode = null;
        BaseFuncBO laseObject = null;
        for (BaseFuncBO bo : this.body) {
            if (bo instanceof IfBO) {
                IfBO ifNode = (IfBO) bo;
                String ifSql = "";
                if (ifNode.getFun() != null && lastIfNode != null && FUN_ELSE_ENUM.contains(ifNode.getFun())) {   // fun
                    if (ELSE.equals(ifNode.getFun()) && ELSE.equals(lastIfNode.getFun())) {
                        throw new MultipleElseException();          // 重复else
                    }
                    if (lastIfNode.isTestResult()) {       // 上一个if是true，下面肯定没戏唱了，直接返回空
                        continue;
                    } else {
                        ifSql = ifNode.complieEntity(allVar, sqlVar, sql, lastObject);
                    }
                } else {                // if
                    if (ifNode.getFun() != null && FUN_ELSE_ENUM.contains(ifNode.getFun())) {
                        throw new FirstIfElseException();
                    }
                    ifSql = ifNode.complieEntity(allVar, sqlVar, sql, lastObject);
                }
                lastIfNode = ifNode;
                laseObject = bo;
                comSql.append(ifSql);
            } else {
                String ss = bo.complieEntity(allVar, sqlVar, sql, laseObject);
                laseObject = bo;
                comSql.append(ss);
            }
        }
        return comSql.toString();
    }
}
